<template>
    <div>
        <el-table
            :data="source"
            class="widget-list"
            @sort-change="handleSortChange"
            @selection-change="handleSelectChange">
            <el-table-column type="selection" width="40" v-if="check"></el-table-column>

            <el-table-column label="标题" prop="name" width="240">
                <template slot-scope="{row}">
                    <div class="flex flex-wrap" :class="titleAlign">
                        <div class="w-full title" @click="fetchDetail(row._id)">
                            <div class="w-full text">{{ row.title }}</div>
                        </div>
                        <div v-if="popular" class="popular w-full">
                            <i class="iconfont icon-eye"></i>
                            <span>{{ row.statistics ? row.statistics.pgNum : 0 }}</span>
                            <i class="iconfont icon-star"></i>
                            <span>{{ row.statistics ? row.statistics.favNum : 0 }}</span>
                            <i class="iconfont icon-share"></i>
                            <span>{{ row.statistics ? row.statistics.shaNum : 0 }}</span>
                        </div>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="分类" align="center">
                <template slot-scope="{row}">
                    <template v-if="changeType">
                        <div v-for="(v, i) in row.cats" :key="i" class="text-grey font-light">{{ v.catName }}</div>
                        <div style="color: #02A7FB; cursor: pointer" @click="$refs.dialog.open(row._id, row.cats)" v-if="row.cats && row.cats.length">更改</div>
                    </template>

                    <template v-else>
                        <div class="text-grey font-light">{{ row.cats.map(el => el.catName).join('、') }}</div>
                    </template>
                </template>
            </el-table-column>

            <el-table-column label="作者" prop="creatorName" align="center" width="80" class="font-light" v-if="check">
                <template slot-scope="{row}">
                    {{ row.hide ? '匿名' : row.creatorName }}
                </template>
            </el-table-column>

            <el-table-column label="发布时间" align="center" width="180" sortable="custom" prop="updateTime">
                <template slot-scope="{row}">
                    <span class="text-grey font-light">{{ row.createTime | formatDate('yy-mm-ss hh:mm:ss') }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="240" v-if="cancel || modify || del || past">
                <template slot-scope="{row, $index}">
                    <el-button type="text" style="color: #02A7FB" @click="onCancel(row.id)" v-if="cancel">撤销</el-button>
                    <el-button type="text" style="color: #02A7FB" @click="onModify(row.id)" v-if="modify">编辑</el-button>
                    <el-button type="text" style="color: #E33A4F" @click="onDelete(row.id)" v-if="del">删除</el-button>
                    <!-- <el-button type="text" style="color: #E33A4F" v-if="del" v-popover:popover>删除</el-button> -->

                    <template v-if="past">
                        <el-button type="text" style="color: #02A7FB" @click="onPast(row.id)">通过</el-button>
                        <el-button type="text" style="color: #E33A4F" @click="onPast(row.id, false)">不通过</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <!-- 改变类目 -->
        <change-category ref="dialog" v-model="update"></change-category>

        <!-- 预览 -->
        <preview :category-text="categoriesText" :labels="labels" ref="preview"></preview>
    </div>
</template>

<script>
    import ChangeCategory from '../widget/ChangeCategory';
    import Preview from '../../components/widget/Preview';
    import {getHelpCategorise} from '../../config/Cache';

    export default {
        components: {
            Preview,
            ChangeCategory
        },
        props: {
            // 数据
            source: {
                type: Array,
                default: () => {
                    return [];
                }
            },
            popular: {
                type: Boolean,
                default: false
            },
            cancel: {
                type: Boolean,
                default: false
            },
            modify: {
                type: Boolean,
                default: false
            },
            del: {
                type: Boolean,
                default: false
            },
            check: {
                type: Boolean,
                default: false
            },
            past: {
                type: Boolean,
                default: false
            },
            changeType: {
                type: Boolean,
                default: false
            },
            value: null
        },
        data() {
            return {
                selected: [],
                update: false,
                types: [],
                labels: [],
                options: [],
                intervalId: {}
            };
        },
        computed: {
            titleAlign() {
                if (this.popular) return 'content-between';
                if (this.del) return '';
                return 'items-center';
            },
            categoriesText() {
                return this.types
                    .filter(el => el)
                    .map(ele => this.findName(ele));
            }
        },
        watch: {
            update(val) {
                if (!val) return;

                this.$emit('input', true);
                this.update = false;
            }
        },
        methods: {
            clear() {
                    const len = Object.values(this.intervalId).filter(el => el);
                    if (len) {
                        const arrays = Object.entries(this.intervalId).filter(el => el[1]);
                        arrays.forEach(el => clearInterval(this.intervalId[el[0]]));
                    }
            },
            onCancel(id) {
                this.postData(id, 0);
            },
            onDelete(id) {
                const ready = this.$route.path.includes('ready');
                const text =  '本条帮助将永久删除，请谨慎操作。';

                Ele.$confirm(text, '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    API.delete('help/article/' + id).then(res => {
                        Ele.$message.success('删除成功');
                        this.$emit('input', true);
                    });

                }).catch(() => {
                    Ele.$message('取消删除');
                });
            },
            onPast(id, status = true) {
                let audit = status ? 3 : 0;
                if (!status) {
                    Ele.$prompt('确认该应用审核不通过？ 请填写审核意见', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消审核'
                    }).then(({ value }) => {
                        console.log(value);
                        this.postData(id, audit, value);
                    }).catch(() => {
                        Ele.$message({
                            type: 'info',
                            message: '取消'
                        });
                    });
                } else {
                    this.postData(id, audit);
                }
            },
            onModify(itemId) {
                // 'ready_modify': 修改中 - midify, 修改完成 - finish
                LocalStore.set('ready_modify_' + itemId, 'modify');
                let times = 0;
                this.intervalId[itemId] = setInterval(() => {
                    if (LocalStore.get('ready_modify_' + itemId) === 'finish') {
                        this.$emit('input', true);
                        clearInterval(this.intervalId[itemId]);
                    }
                }, 1000 * 1);
                // this.$router.push({
                //     name: 'Application.Edit',
                //     query: {
                //         id: itemId
                //     }
                // })
                window.open(location.origin + '/admin/help/edit/' + itemId, '_blank');
            },
            postData(id, status, mesg = '') {
                // audit: 0.初始状态 1.审核中 2.审核未通过 3.审核通过
                let data = {
                    audit: status,
                    ids: id,
                    msg: mesg
                };

                API.post('manage/applications/audit', data).then(res => {
                    Ele.$message.success('操作成功');
                    this.$emit('input', true);
                });
            },
            handleSelectChange(section) {
                const ids = section.map(el => el.id).join(',');
                this.$emit('emitSelected', ids);
            },
            handleSortChange(val) {
                console.log(val)
                let _order = val.order ? val.order : 'ascending'
                this.$emit('sortBy', _order);
            },
            // handle preview date
            fetchDetail(id) {
                this.loading = true;
                API.get('help/article/' + id).then(res => {
                    this.types = res.cats.map(el => this.findCategoryArray(el.catId));
                    //this.labels = res.labels.filter(el => el);

                    this.$refs.preview.open(res);
                }).finally(() => this.loading = false);
            },
            async fetchCategory() {
                this.options = await getHelpCategorise();
            },
            findName(array) {
                return this.options.find(el => el.id === array[array.length - 1]).text;
            },
            findCategoryArray(sourceId) {
                const options = this.options;
                let arr = [];
                let isFinish = true;
                let id = sourceId;

                while (isFinish) {
                    const element = options.find(el => el.id === id);
                    if (element) {
                        arr.unshift(element.id);
                        if (element.parentid) {
                            id = element.parentid;
                        } else {
                            isFinish = false;
                        }
                    } else {
                        isFinish = false;
                    }
                }
                return arr;
            },
        },
        created() {
            this.fetchCategory();
        },
    }
</script>

<style lang="scss">
    .widget-list {
        font-size: 16px;

        .item {
            width: 270px;
            height: 150px;
            margin-left: -10px;
            display: inline-block;
            vertical-align: top;

            &.img {
                background: transparent no-repeat center/cover;

                &:hover {
                    width: 270px;
                    height: 150px;
                    position: relative;
                    cursor: pointer;

                    &::after {
                        content: '预览';
                        width: 270px;
                        height: 150px;
                        color: #fff;
                        line-height: 150px;
                        text-align: center;
                        display: inline-block;
                        background-color: rgba(0, 0, 0, .1);
                    }
                }
            }
        }

        .title {
            &:hover {
                cursor: pointer;
                color: #02a4fc;
            }

            .text {
                font-size: 18px;
            }
        }
    }
</style>
